package org.example.order.domain.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.time.DateUtils;
import org.example.api.order.constant.TradeOrderState;
import org.example.order.domain.entity.TradeOrder;
import org.example.order.infrastructure.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Nullable;
import java.util.Date;
import java.util.List;

@Service
public class OrderReadService extends ServiceImpl<OrderMapper, TradeOrder> {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 按照订单号查询订单信息
     *
     * @param orderId
     * @return
     */
    public TradeOrder getOrder(String orderId) {
        return orderMapper.selectByOrderId(orderId);
    }

    /**
     * 分页查询已经超时的订单
     *
     * @param pageSize
     * @param buyerIdTailNumber 买家 ID 的尾号
     * @param minId
     * @return
     */
    public List<TradeOrder> pageQueryTimeoutOrders(int pageSize, @Nullable String buyerIdTailNumber, Long minId) {
        QueryWrapper<TradeOrder> wrapper = new QueryWrapper<>();
        wrapper.in("order_state", TradeOrderState.CONFIRM.name(), TradeOrderState.CREATE.name());
        wrapper.lt("gmt_create", DateUtils.addMinutes(new Date(), -TradeOrder.DEFAULT_TIME_OUT_MINUTES));
        if (buyerIdTailNumber != null) {
            wrapper.likeRight("reverse_buyer_id", buyerIdTailNumber);
        }
        if (minId != null) {
            wrapper.ge("id", minId);
        }
        wrapper.orderBy(true, true, "gmt_create");
        wrapper.last("limit " + pageSize);

        return this.list(wrapper);
    }
}
